<template>
  <wd-form ref="form" :model="model" :rules="rules" class="register-form">
    <wd-cell-group border>
      <wd-input
        :label="t('pages.sys.proxy.api')"
        label-width="100px"
        prop="api"
        :placeholder="t('common.input')"
        clearable
        v-model="model.api"
      />
      <wd-input
        :label="t('pages.sys.proxy.signin')"
        label-width="100px"
        prop="signin-"
        :placeholder="t('common.input')"
        clearable
        v-model="model['signin-']"
      />
      <wd-input
        :label="t('pages.sys.proxy.signalr')"
        label-width="100px"
        prop="signalr"
        :placeholder="t('common.input')"
        clearable
        v-model="model['signalr']"
      />
      <wd-input
        :label="t('pages.sys.proxy.file')"
        label-width="100px"
        prop="file"
        :placeholder="t('common.input')"
        clearable
        v-model="model['file']"
      />
      <wd-input
        :label="t('pages.sys.proxy.upload')"
        label-width="100px"
        prop="upload"
        :placeholder="t('common.input')"
        clearable
        v-model="model['upload']"
      />
      <wd-cell title-width="0px">
        <view class="register-form-footer">
          <wd-button type="info" @click="handleCancel">{{ t('common.cancel') }}</wd-button>
          <wd-button type="primary" @click="handleOk">{{ t('common.ok') }}</wd-button>
        </view>
      </wd-cell>
    </wd-cell-group>
  </wd-form>
</template>

<script lang="ts" setup>
  import { FormRules } from 'wot-design-uni/components/wd-form/types';

  import { useI18n } from '@/locale/index';
  import { ProxyState, useProxyStore } from '@/store/modules/proxy';
  import { isHttpUrl } from '@/utils/is';

  const { t } = useI18n();
  const proxyStore = useProxyStore();

  const form = ref();

  const validator = (val: string) => {
    if (!val) {
      return Promise.reject(new Error(t('common.input')));
    }
    if (!isHttpUrl(val)) {
      return Promise.reject(new Error(t('common.formatError')));
    }
    return Promise.resolve();
  };
  const model = ref<ProxyState>({});
  const rules: FormRules = {
    api: [{ required: true, validator, message: '' }],
    'signin-': [{ required: true, validator, message: '' }],
    signalr: [{ required: true, validator, message: '' }],
    file: [{ required: true, validator, message: '' }],
    upload: [{ required: true, validator, message: '' }],
  };

  onMounted(() => {
    model.value = { ...proxyStore.state };
  });

  function handleOk() {
    form.value
      .validate()
      .then(({ valid }) => {
        if (valid) {
          proxyStore.state = { ...proxyStore.state, ...model.value };
          handleCancel();
        }
      })
      .catch((error: any) => {
        console.error(error);
      });
  }

  function handleCancel() {
    uni.navigateBack();
  }
</script>

<style lang="scss" scoped>
  @import './index';
</style>
